package com.recharge.web.controller;


import com.recharge.common.annotation.OperationLogDetail;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.enums.OperationLogType;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.web.ObjectResponse;
import com.recharge.common.util.FunctionUtil;
import com.recharge.domain.query.ProviderOrderQueryDO;
import com.recharge.domain.vo.ProviderOrderDO;
import com.recharge.service.ProviderOrderService;
import io.swagger.annotations.ApiOperation;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@RestController
@RequestMapping("/provider-order")
public class ProviderOrderController extends BaseController {
	@Autowired
    private ProviderOrderService providerOrderService;

	@Value("${file.provider-order.template}")
	private String fileTemplatePath;


	@RequiresPermissions("provider-order:page")
	 @RequestMapping(value="/page.html", method = RequestMethod.POST)
	 @ApiOperation(value="分页查询供货单", notes="")
	public @ResponseBody  ObjectResponse<PageDO> page(@RequestBody ProviderOrderQueryDO query) {

	 	ObjectResponse<PageDO> response = new ObjectResponse<>();

	 	ResultDO result = providerOrderService.find(query);

	 	if(result.isSuccess()) {
			response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}

	 	return response;
	 }

	@RequiresPermissions("provider-order:reportOrder")
	@RequestMapping(value="/reportOrder.html", method = RequestMethod.POST)
	@ApiOperation(value="统计供货单", notes="")
	public @ResponseBody  ObjectResponse<PageDO> reportOrder(@RequestBody ProviderOrderQueryDO query) {

		ObjectResponse<PageDO> response = new ObjectResponse<>();

		ResultDO result = providerOrderService.reportOrder(query);

		if(result.isSuccess()) {
			response.setData((PageDO) result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}

		return response;
	}

	@RequiresPermissions("provider-order:vouchingProviderOrder")
	@RequestMapping(value="/vouchingProviderOrder.html", method = RequestMethod.POST)
	@ApiOperation(value="单笔核单", notes="")
	public @ResponseBody  ObjectResponse<Object> vouchingProviderOrder(@RequestBody ProviderOrderDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		ResultDO result = providerOrderService.vouchingProviderOrder(param);
		if(result.isSuccess()) {
			response.setData(result.getModel(ResultDO.FIRST_MODEL_KEY));
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("provider-order:edit")
	@RequestMapping(value="/edit.html", method = RequestMethod.POST)
	@ApiOperation(value="同步", notes="")
	public @ResponseBody  ObjectResponse<Object> edit(@RequestBody ProviderOrderDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		ResultDO result = providerOrderService.edit(param, getUserName());
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("provider-order:vouchingBatch")
	@RequestMapping(value="/vouchingBatch.html", method = RequestMethod.POST)
	@ApiOperation(value="批量核单", notes="")
	public @ResponseBody  ObjectResponse<Object> vouchingBatch(@RequestBody ProviderOrderDO param) {
		ObjectResponse<Object> response = new ObjectResponse<>();
		if(StringUtils.isEmpty(param.getIds())) {
			response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
			response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
			return response;
		}
		ResultDO result = providerOrderService.vouchingBatch(param.getIds().split(","), getUserName());
		if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
		return response;
	}

	@RequiresPermissions("provider-order:updateBatch")
	@OperationLogDetail(detail = "批量供货单成功，失败。", operationType = OperationLogType.CONFIRM_PROVIDER_ORDER_STATUS)
	@RequestMapping(value="/updateBatch.html", method = RequestMethod.POST)
	@ApiOperation(value="批量供货单成功，失败。", notes="")
	public @ResponseBody  ObjectResponse<Object> updateBatch(@RequestBody ProviderOrderDO param) {
	 	ObjectResponse<Object> response = new ObjectResponse<>();
	 	if(StringUtils.isEmpty(param.getIds()) || param.getStatus() == null || param.getIsOver() == null) {
	 		response.setStatus(ErrorCode.PARAM_GET_ERROR.getCode());
			response.setMsg(ErrorCode.PARAM_GET_ERROR.getMsg());
			return response;
	 	}
	 	ResultDO result = providerOrderService.updateBatch(param.getResetType(), param.getStatus(), param.getIds().split(","), param.getIsOver(), null, getUserName());
	 	if(result.isSuccess()) {
			response.setData(null);
		} else {
			response.setStatus(result.getErrorCode().getCode());
			response.setMsg(result.getErrorCode().getMsg());
		}
	 	return response;
	}

	@RequiresPermissions("provider-order:download")
	@RequestMapping(value="/download.html", method = RequestMethod.POST)
	@ApiOperation(value="供货订单下载", notes="")
	public void download(@RequestBody ProviderOrderQueryDO query, HttpServletResponse response) {

		ResultDO result = providerOrderService.findList(query);
		List<ProviderOrderDO> list= (List<ProviderOrderDO>) result.getModel(ResultDO.FIRST_MODEL_KEY);
		Map map = new HashMap();
		map.put("data",list);
		map.put("fun", new FunctionUtil());
		try{
			InputStream is = new FileInputStream(fileTemplatePath);
			// 实例化 XLSTransformer 对象
			XLSTransformer xlsTransformer = new XLSTransformer();
			// 获取 Workbook ，传入 模板 和 数据
			Workbook workbook =  xlsTransformer.transformXLS(is,map);

			// 设置文件名
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("商品列表.xls" ,"UTF-8"));
			// 写出文件
			OutputStream os = new BufferedOutputStream( response.getOutputStream() );
			// 输出
			workbook.write(os);
			// 关闭和刷新管道，不然可能会出现表格数据不齐，打不开之类的问题
			is.close();
			os.flush();
			os.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
